package com.wstuo.common.tools.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.noticeRule.dto.NoticeInfoDTO;
import com.wstuo.common.noticeRule.service.INoticeRuleService;
import com.wstuo.common.tools.dao.IEventTaskDAO;
import com.wstuo.common.tools.dto.CostDTO;
import com.wstuo.common.tools.dto.EventTaskDTO;
import com.wstuo.common.tools.dto.EventTaskQueryDTO;
import com.wstuo.common.tools.dto.HistoryRecordDTO;
import com.wstuo.common.tools.entity.EventTask;
import com.wstuo.common.tools.util.ToolsConstant;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;

/**
 * 事件任务Service class
 * 
 * @author WSTUO
 * 
 */
public class EventTaskService implements IEventTaskService {

	@Autowired
	private IEventTaskDAO eventTaskDAO;
	@Autowired
	private INoticeRuleService noticeRuleService;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IHistoryRecordService historyRecordService;
	@Autowired
	private AppContext appctx;
	@Autowired
	private ICostService costService;
	/**
	 * 分页查询任务
	 * 
	 * @param queryDto
	 * @param start
	 * @param limit
	 * @return PageDTO
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findPagerEventTask(EventTaskQueryDTO queryDto, int start,
			int limit) {
		PageDTO p = eventTaskDAO.findPagerEventTask(queryDto, start, limit);
		List<EventTask> entities = (List<EventTask>) p.getData();
		List<EventTaskDTO> dtos = new ArrayList<EventTaskDTO>(entities.size());
		for (EventTask entity : entities) {
			EventTaskDTO eventTaskDto = new EventTaskDTO();
			entity2dto(entity, eventTaskDto);
			dtos.add(eventTaskDto);
		}
		p.setData(dtos);
		return p;
	}

	/**
	 * 保存事件任务
	 * 
	 * @param dto
	 */
	@Transactional
	public void saveEventTask(EventTaskDTO dto) {
		String[] owners = null;
		if(dto!=null && dto.getOwner() != null){
			owners = dto.getOwner().split(";");
		}
		User taskCreator = null;
		if (dto!=null && dto.getCreator() != null) {
			taskCreator = userDAO.findUserByLoginName(dto.getCreator());
		}
		if(dto!=null && owners!=null){
			for (int i = 0; i < owners.length; i++) {
				if(StringUtils.hasText(owners[i])){
					EventTask eventTask = new EventTask();
					dto.setOwner(owners[i]);
					if (dto!=null && dto.getOwner() != null) {
						eventTask.setOwner(userDAO.findUserByLoginName(dto.getOwner()));
					}
					dto2entity(dto, eventTask);
					eventTask.setTaskCreator(taskCreator);
					eventTask.setCreateTime(new Date());
					eventTaskDAO.save(eventTask);
					dto.setTaskId(eventTask.getTaskId());
					// 保存历史记录
					saveTaskhistoryRecord(dto, "Add Task", "itsm.task");
					eventTaskNotice("taskNoticeOwner", eventTask, dto);
				}
			}
		}
		
	}

	/**
	 * 编辑事件任务
	 * 
	 * @param dto
	 */
	@Transactional
	public void editEventTask(EventTaskDTO dto) {
		if(dto!=null){
			EventTask eventTask = eventTaskDAO.findById(dto.getTaskId());
			if(eventTask!=null){
				dto.setOwner(dto.getOwner());
				dto2entity(dto, eventTask);
				if (dto!=null&&dto.getOwner() != null) {
					eventTask.setOwner(userDAO.findUserByLoginName(dto.getOwner()));
				}
				if (dto!=null&&dto.getCreator() != null) {
					eventTask.setTaskCreator(userDAO.findUserByLoginName(dto.getCreator()));
				}
				eventTaskDAO.merge(eventTask);
				// 保存历史记录
				saveTaskhistoryRecord(dto, "Edit Task", "itsm.task");
			}
		}
	}

	/**
	 * 删除事件任务
	 * 
	 * @param ids
	 */
	@Transactional
	public void deleteEventTask(final Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				EventTask entity = eventTaskDAO.findById(id);
				List<CostDTO> dtos = costService.findTaskCostWithTaskId(id);
				costService.deleteCost(dtos);
				historyRecordService.deleteHistoryRecord(id, ToolsConstant.TYPE_OTHER_IS_TASK);
				eventTaskDAO.delete(entity);
			}
		}
		//eventTaskDAO.deleteByIds(ids);
	}

	/**
	 * 判断同一时间段任务是否冲突
	 * 
	 * @param eventTaskDTO
	 * @return boolean
	 */
	@Transactional
	public boolean timeConflict(EventTaskDTO eventTaskDTO) {
		boolean blo = false;
		String[] owners = eventTaskDTO.getOwner().split(";");
		for (int i = 0; i < owners.length; i++) {
			eventTaskDTO.setOwner(owners[i]);
			if (eventTaskDAO.findSameTimeEventTask(eventTaskDTO)) {
				blo = true;
			}
		}
		return blo;
	}

	/**
	 * 根据ID查找EventTask
	 * 
	 * @param taskId
	 * @return EventTaskDTO
	 */
	@Transactional
	public EventTaskDTO findEventTaskById(Long taskId) {
		EventTask eventTask = eventTaskDAO.findById(taskId);
		EventTaskDTO eventTaskDTO = new EventTaskDTO();
		entity2dto(eventTask, eventTaskDTO);
		return eventTaskDTO;
	}

	/**
	 * 事件任务通知
	 * 
	 * @param noticeRuleNo
	 * @param eventTask
	 * @param owner
	 * @param creator
	 * @param operator
	 */
	private void eventTaskNotice(String noticeRuleNo, EventTask eventTask,
			EventTaskDTO dto) {
		NoticeInfoDTO noticeInfoDto = new NoticeInfoDTO();
		noticeInfoDto.setNoticeRuleNo(noticeRuleNo);
		noticeInfoDto.setOwner(userDAO.findUniqueBy("loginName", dto.getOwner()));
		noticeInfoDto.setRequester(userDAO.findUniqueBy("loginName",dto.getCreator()));
		entity2dto(eventTask, dto);
		noticeInfoDto.setVariables(dto);
		noticeRuleService.commonNotice(noticeInfoDto);
	}


	/**
	 * 判断是否有删除权限
	 * 
	 * @param ids
	 * @return boolean
	 */
	public boolean findTaskByIds(Long[] ids) {
		boolean blo = true;
		String operator = appctx.getCurrentLoginName();
		for (int i = 0; i < ids.length; i++) {
			EventTask eventTask = eventTaskDAO.findById(ids[i]);
			if (!operator.equals(eventTask.getCreator())) {
				blo = false;
			}
		}
		return blo;
	}

	/**
	 * entity2dto
	 * 
	 * @param task
	 * @param dto
	 */
	private void entity2dto(EventTask task, EventTaskDTO dto) {
		if (task != null) {
			dto.setEno(task.getEno());
			dto.setEventType(task.getEventType());
			dto.setTaskId(task.getTaskId());
			dto.setEtitle(task.getTitle());
			dto.setStartTime(task.getStartTime());
			dto.setEndTime(task.getEndTime());
			dto.setAllDay(task.getAllDay());
			if (task.getOwner() != null) {
				dto.setOwner(task.getOwner().getFullName());
				dto.setOwnerLoginName(task.getOwner().getLoginName());
			}
			dto.setIntroduction(task.getIntroduction());
			dto.setLocation(task.getLocation());
			dto.setTaskStatus(task.getTaskStatus());
			if (task.getTaskCreator() != null) {
				dto.setCreator(task.getTaskCreator().getFullName());
				dto.setCreatorLoginName(task.getTaskCreator().getLoginName());
			}
			dto.setRealStartTime(task.getRealStartTime());
			dto.setRealEndTime(task.getRealEndTime());
			dto.setRealFree(task.getRealFree());
			dto.setTreatmentResults(task.getTreatmentResults());
			//通知模板需要的变量
			dto.setEtitle(task.getTitle());
			dto.setEdesc(task.getIntroduction());
			dto.setCreatedByName(task.getCreator());
			if(task.getStartTime()!=null && task.getEndTime()!=null){
				dto.setPlanTime(TimeUtils.format(task.getStartTime(), TimeUtils.DATE_PATTERN)+"——>"
						+TimeUtils.format(task.getEndTime(),TimeUtils.DATE_PATTERN));
			}
			if(task.getCreateTime() !=null){
				dto.setCreatedOn(task.getCreateTime());
			}else{
				dto.setCreatedOn(new Date());
			}
		}
	}

	/**
	 * dto2entity
	 * 
	 * @param taskDto
	 * @param task
	 */
	private void dto2entity(EventTaskDTO taskDto, EventTask task) {
		if(taskDto!=null){
			task.setEno(taskDto.getEno());
			task.setEventType(taskDto.getEventType());
			task.setAllDay(taskDto.getAllDay());
			task.setEndTime(taskDto.getEndTime());
			task.setStartTime(taskDto.getStartTime());
			task.setIntroduction(taskDto.getIntroduction());
			task.setTitle(taskDto.getEtitle());
			task.setLocation(taskDto.getLocation());
			task.setTaskStatus(taskDto.getTaskStatus());
			task.setCreator(taskDto.getCreator());
			task.setRealStartTime(taskDto.getRealStartTime());
			task.setRealEndTime(taskDto.getRealEndTime());
			task.setRealFree(taskDto.getRealFree());
			task.setTreatmentResults(taskDto.getTreatmentResults());
		}
		
	}

	/**
	 * 保存任务的历史记录
	 * 
	 * @param dto
	 * @param logDetails
	 * @param eventType
	 */
	private void saveTaskhistoryRecord(EventTaskDTO dto, String logDetails,
			String eventType) {
		HistoryRecordDTO hrDto = new HistoryRecordDTO();
		hrDto.setEno(dto.getTaskId());
		hrDto.setLogDetails(logDetails);
		hrDto.setEventType(eventType);
		hrDto.setCreatedTime(new Date());
		hrDto.setOperator(dto.getOperator());
		historyRecordService.saveHistoryRecord(hrDto);
	}
}
